import ntplib
import subprocess
import datetime

def ntp_client():
    # 创建 NTPClient 实例
    client = ntplib.NTPClient()
    hosts = ['0.cn.pool.ntp.org', '1.cn.pool.ntp.org', '2.cn.pool.ntp.org', '3.cn.pool.ntp.org']

    for host in hosts:
        try:
            # 查询 NTP 服务器，并返回对象
            response = client.request(host, port='ntp', version=4, timeout=5)
            if response:
                break
        except Exception as e:
            pass

    # 获取服务器返回的时间戳
    timestamp = response.tx_time

    # 将时间戳转换为可读的日期和时间格式
    dt = datetime.datetime.fromtimestamp(timestamp)
    _date = dt.strftime("%m-%d-%y")
    _time = dt.strftime("%H:%M:%S")

    print("调整前的时间是：", datetime.datetime.now())

    # 关闭网络时间同步
    subprocess.run(['sudo', 'systemsetup', '-setusingnetworktime', 'off'])
    print(_date)
    # 设置日期
    subprocess.run(['sudo', 'date', _date])

    # 设置时间
    print(_time)
    subprocess.run(['sudo', 'date', _time])

    print("调整后的时间是：", datetime.datetime.now())

if __name__ == '__main__':
    ntp_client()
